<?php

namespace app\admin\service;


use app\admin\model\ActiveUserSta;
use think\Db;

/**
 * 活跃用户统计管理-服务类
 * Class ActiveUserStaService
 * @package app\admin\service
 */
class ActiveUserStaService extends BaseService
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new ActiveUserSta();
    }

    /**
     * 获取数据列表
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];
        $sort = 'id desc';
        $is_sql = 0;

        $type = $param['type'] ?? 1;
        switch ($type) {
            case 2://周
                $group = 'year,week';
                break;
            case 3://月
                $group = 'year,month';
                break;
            case 4://年
                $group = 'year';
                break;
            default://日
                $group = 'year,month,day';
                break;
        }
        $map['type'] = $type;

        //获取数据总数
        $count = $this->model
            ->where($map)
            ->group($group)
            ->count();
        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }
        $list = [];
        if ($count > 0) {
            $field = [
                'sum(user_num)' => 'user_num',
                'sum(active_user_num)' => 'active_user_num',
                'sum(terminal_num)' => 'terminal_num',
                'sum(active_terminal_num)' => 'active_terminal_num',
                'sum(call_terminal_num)' => 'call_terminal_num',
                'sum(gps_num)' => 'gps_num',
                'sum(base_num)' => 'base_num',
                'sum(mix_num)' => 'mix_num',
                'day',
                'week',
                'month',
                'year',
            ];
            $list = $this->model
                ->where($map)
                ->order($sort)
                ->page(PAGE, PERPAGE)
                ->group($group)
                ->field($field)
                ->select();
        }

        //返回结果
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }


    public function delete()
    {
        // 参数
        $param = request()->param();
        // 记录ID
        $ids = getter($param, "id");
        if (empty($ids)) {
            return message("记录ID不能为空", false);
        }
        $ids = (array)$ids;

        $result = ActiveUserSta::destroy($ids);
        if (!$result) {
            return message("删除失败", false);
        }
        return message("删除成功");
    }


    /**
     * 导出Excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function exportExcel()
    {
        $type = request()->param('type');
        // 获取导出的数据源
        $res = $this->getList();
        $list = $res['data'];

        // 实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        // 激活当前的sheet表
        $activeSheet = $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $activeSheet->setCellValue('A1', '平台用户数')
            ->setCellValue('B1', '活跃用户数')
            ->setCellValue('C1', '终端总数')
            ->setCellValue('D1', '活跃终端总数')
            ->setCellValue('E1', '通话终端数')
            ->setCellValue('F1', 'gps点数')
            ->setCellValue('G1', '基站点数')
            ->setCellValue('H1', '混合点数')
            ->setCellValue('I1', '统计周期');

        //设置列水平居左
        $activeSheet->getStyle('A')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('B')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('C')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('D')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('E')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('F')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('G')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('H')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('I')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

        // 设置单元格宽度
        $activeSheet->getColumnDimension('A')->setWidth(20);
        $activeSheet->getColumnDimension('B')->setWidth(20);
        $activeSheet->getColumnDimension('C')->setWidth(20);
        $activeSheet->getColumnDimension('D')->setWidth(20);
        $activeSheet->getColumnDimension('E')->setWidth(20);
        $activeSheet->getColumnDimension('F')->setWidth(20);
        $activeSheet->getColumnDimension('G')->setWidth(20);
        $activeSheet->getColumnDimension('H')->setWidth(20);
        $activeSheet->getColumnDimension('I')->setWidth(20);

        // 循环刚取出来的数组，将数据逐一添加到excel表格。
        for ($i = 0; $i < count($list); $i++) {
            $activeSheet->setCellValue('A' . ($i + 2), $list[$i]['user_num']);
            $activeSheet->setCellValue('B' . ($i + 2), $list[$i]['active_user_num']);
            $activeSheet->setCellValue('C' . ($i + 2), $list[$i]['terminal_num']);
            $activeSheet->setCellValue('D' . ($i + 2), $list[$i]['active_terminal_num']);
            $activeSheet->setCellValue('E' . ($i + 2), $list[$i]['call_terminal_num']);
            $activeSheet->setCellValue('F' . ($i + 2), $list[$i]['gps_num']);
            $activeSheet->setCellValue('G' . ($i + 2), $list[$i]['base_num']);
            $activeSheet->setCellValue('H' . ($i + 2), $list[$i]['mix_num']);

            switch ($type) {
                case 2://周
                    $type_str = $list[$i]['year'] . '-' . $list[$i]['week'];
                    break;
                case 3://月
                    $type_str = $list[$i]['year'] . '-' . $list[$i]['month'];
                    break;
                case 4://年
                    $type_str = $list[$i]['year'];
                    break;
                default://日
                    $type_str = $list[$i]['year'] . '-' . $list[$i]['month'] . '-' . $list[$i]['day'];
                    break;
            }
            $activeSheet->setCellValue('I' . ($i + 2), $type_str);
        }
        // 设置保存的Excel表格名称
        $filename = '活跃用户统计_' . date('YmdHis', time()) . ".xlsx";
        // 设置当前激活的sheet表格名称
        $activeSheet->setTitle('活跃用户统计');
        // 保存本地文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $savePath = UPLOAD_TEMP_PATH . "/" . $filename;
        $objWriter->save($savePath);

        // 文件地址
        $filePath = get_image_url(str_replace(PUBLIC_PATH, "", $savePath));
        return message("操作成功", true, $filePath);
    }
}

